package com.dinetech.ejecutor;

import java.util.ArrayList;

import com.dinetech.dao.SpinnerVariosAdapter;
import com.dinetech.dao.UbicacionAdapter;
import com.dinetech.dao.WSEvento;
import com.dinetech.entidades.Personal;
import com.dinetech.entidades.Session;
import com.dinetech.entidades.Ubicacion;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class EventoDestete extends Fragment implements OnClickListener{

	private static final String ID_GALPON="0";
	Spinner cbxUbicDestete, cbxGenero, cbxRespDestete;
	EditText txtCantMD, txtCantHD, txtObs;
	LinearLayout lM, lH;
	Button btnGrabarD;
	Personal perD = Personal.getInstance();
	int idUsuario, idUbicacion, idGenero, idGalpon;
	Session ses= Session.getInstance();
	
	public static EventoDestete newInstance (int IdGalpon){
		
		EventoDestete eventoD = new EventoDestete();
		
		Bundle bundle = new Bundle();
		bundle.putInt(ID_GALPON, IdGalpon);
		eventoD.setArguments(bundle);
		eventoD.setRetainInstance(true);
		
		return eventoD;
	}
	
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		
		ViewGroup view = (ViewGroup)inflater.inflate(R.layout.evento_destete_y_sexaje,container, false);
		
		cbxUbicDestete = (Spinner)view.findViewById(R.id.cbxPozaDyS);
		cbxGenero = (Spinner)view.findViewById(R.id.cbxSexoDyS);
		cbxRespDestete = (Spinner)view.findViewById(R.id.cbxResponsableDyS);
		txtCantMD = (EditText)view.findViewById(R.id.txtCantMachosDyS1);
		txtCantHD =(EditText)view.findViewById(R.id.txtCantHembrasDyS);
		txtObs = (EditText)view.findViewById(R.id.txtComentarioDyS);
		btnGrabarD = (Button)view.findViewById(R.id.btnDestete);
		lM = (LinearLayout)view.findViewById(R.id.linearLHCantMachosD);
		lH = (LinearLayout)view.findViewById(R.id.linearLHCantHembrasD);
		btnGrabarD.setOnClickListener(this);
		this.idGalpon = getArguments().getInt(ID_GALPON);
		
		new listarUbicacion().execute();
		llenarSpinner();
		
		return view;
	}

	
	private void llenarSpinner(){
						
		SpinnerVariosAdapter adaptadorG = new SpinnerVariosAdapter(EventoDestete.this, ses.getLISTA_GENERO());
		cbxGenero.setAdapter(adaptadorG);
		cbxGenero.setOnItemSelectedListener(new SpinnerListenerGenero());
		
		
		SpinnerVariosAdapter adaptadorRespD = new SpinnerVariosAdapter(EventoDestete.this, ses.getLISTA_RESPONSABLE());
		cbxRespDestete.setAdapter(adaptadorRespD);
		cbxRespDestete.setOnItemSelectedListener(new SpinnerListenerResp());
		
		for(int i=0; i <  adaptadorRespD.getCount(); i++){
			int idRA=(int)(long)adaptadorRespD.getItemId(i) ;
			idUsuario = perD.getIdPersonal();
			if( idRA == idUsuario){
				cbxRespDestete.setSelection(i);					
			}	        
		}
		
	}
	
	private void refrescarDestete(){
		
		new listarUbicacion().execute();
		txtCantMD.setText("");
		txtCantHD.setText("");
		txtObs.setText("");
		llenarSpinner();
	}
	
	public class SpinnerListenerUbic implements OnItemSelectedListener {
	      
        public void onItemSelected(AdapterView<?> parent,
            View view, int pos, long id) {
        
            int convert=Integer.parseInt( Long.toString(id));
            idUbicacion= convert;	 
            if (idUbicacion==0){
				btnGrabarD.setEnabled(false);
			}
        }

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			
			
		}
	}
	
	public class SpinnerListenerResp implements OnItemSelectedListener {
	      
        public void onItemSelected(AdapterView<?> parent,
            View view, int pos, long id) {
        
            int convert=Integer.parseInt( Long.toString(id));
            idUsuario= convert;	            	         
        }

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			
			
		}
	}
	
	public class SpinnerListenerGenero implements OnItemSelectedListener {
	      
        public void onItemSelected(AdapterView<?> parent,
            View view, int pos, long id) {
        
            int convert=Integer.parseInt( Long.toString(id));
            idGenero = convert;	
            
            if(idGenero==1)
            {
            	txtCantMD.setEnabled(true);
            	txtCantHD.setEnabled(false);
            	txtCantHD.setText("0");
            	txtCantMD.setText("");
            	txtCantMD.requestFocus();
            }
            else if (idGenero==2) {
            	txtCantHD.setEnabled(true);
            	txtCantMD.setEnabled(false);
            	txtCantMD.setText("0");
            	txtCantHD.setText("");
            	txtCantHD.requestFocus();
			}
        }

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			
			
		}
	}
	
	private class listarUbicacion extends AsyncTask<String, Void, ArrayList<Ubicacion>>{

		@Override
		protected ArrayList<Ubicacion> doInBackground(String... params) {
			ArrayList<Ubicacion> listaUbicacion;
			WSEvento wsE = new WSEvento();
			
			listaUbicacion = wsE.ubicacionPorEvento("02", idGalpon, 2, 3, 1, 0, perD.getIdSucursal());
			
			return listaUbicacion;
		}

		@Override
		protected void onPostExecute(ArrayList<Ubicacion> result) {
			super.onPostExecute(result);
			
			UbicacionAdapter adaptadorUbic = new UbicacionAdapter(EventoDestete.this, result);
			cbxUbicDestete.setAdapter(adaptadorUbic);
			cbxUbicDestete.setOnItemSelectedListener(new SpinnerListenerUbic());
			
			
			
		}
		
	}
	
	private class grabarDestete extends AsyncTask<String, Void, String>{
		
		
		@Override
	    protected String doInBackground(String... urls) {

	    	WSEvento we= new WSEvento();
	    		    	
	    	String Msg = we.grabarEvento("01", "02", "0", "0", ses.obtenerFechaActual(), String.valueOf(idUbicacion), "0", Integer.parseInt(txtCantMD.getText().toString()),
	    				Integer.parseInt(txtCantHD.getText().toString()), 0, "0", "0", "0", "0"+String.valueOf(idGenero), 0, txtObs.getText().toString(), idUsuario, 
	    				ses.obtenerFechaActual2(), perD.getIdPersonal(), 0, "0", perD.getIdSucursal(), idGalpon,0,0);
	    	return Msg;
	        	
	    }

	    @Override
	    protected void onPostExecute(String resultadoWS) {
	        super.onPostExecute(resultadoWS);	
	         
	        Toast msg = Toast.makeText(getActivity(), resultadoWS, Toast.LENGTH_LONG);
	        msg.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
	        msg.show();
	        refrescarDestete();
	        
	    }
	}


	@Override
	public void onClick(View v) {
		
		if(idGenero == 1){
			
			if(txtCantMD.getText().length()==0){
				txtCantMD.setText("0");
			}
			
			int cantMachos = Integer.parseInt(txtCantMD.getText().toString());
			
			if(cantMachos < 1){
				AlertDialog.Builder alerta = new AlertDialog.Builder(getActivity());				
				alerta.setTitle("Alerta");				
				alerta.setMessage("No puede ingresar una cantidad menor a 1");				
				alerta.setPositiveButton("OK", 
						new DialogInterface.OnClickListener() {
				     public void onClick(DialogInterface dialog, int which) {
				     }
				    });
				alerta.show();
				txtCantMD.setText("");
			}
			else{
				new grabarDestete().execute();
				txtCantMD.requestFocus();
			}							
		}
		else if(idGenero == 2){
			
			if(txtCantHD.getText().length()==0){
				txtCantHD.setText("0");
			}
			
			int cantHembras = Integer.parseInt(txtCantHD.getText().toString());
			
			if(cantHembras < 1){
				AlertDialog.Builder alerta = new AlertDialog.Builder(getActivity());				
				alerta.setTitle("Alerta");
				alerta.setMessage("No puede ingresar una cantidad menor a 1");
				alerta.setPositiveButton("OK", 
						new DialogInterface.OnClickListener() {
				     public void onClick(DialogInterface dialog, int which) {
				     }
				    });
				alerta.show();
				txtCantHD.setText("");
			}
			else{
				new grabarDestete().execute();
				txtCantHD.requestFocus();
			}
			
		}
		
		
		
		
	}
	
}
